import React from "react";
import { Form, Input, Button, message } from "antd";
import { useNavigate } from "react-router-dom";

import "./Login.css";
import Particles from "react-particles-js"; //粒子效果
import axios from "axios";
import { Navigate } from "react-router-dom"; //重定向

export default function Login() {
  const navigate = useNavigate();
  const onFinish = (values) => {
    /*
    自动开始校验并收集input里的value数据
    */
    console.log("Success:", values);
    //发送数据给后端，且必须后台的开关状态是true的时候才可以,必须全部满足  然后
    axios
      .get(
        `http://localhost:5000/users?username=${values.username}&password=${values.password}&roleState=true&_expand=role`
      )
      .then((res) => {
        console.log(res.data);
        if (res.data.length === 0) {
          message.error("用户名或密码错误");
        } else if (res.data) {
          //正常后台会存一个方便校验的token值，这里用的是个对象，结果是变成[object object]所以要转换一下
          localStorage.setItem("token", JSON.stringify(res.data[0]));
          navigate("/");
        }
      });
  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <div style={{ background: "rgba(35, 39, 65)", height: "100%" }}>
      {/* 粒子效果 */}
      <Particles></Particles>
      <Form
        className="formClass"
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <div className="thHeader">全球新闻发布系统管理</div>
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: "请输入用户名",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密 &nbsp;&nbsp;码"
          name="password"
          rules={[
            {
              required: true,
              message: "请输入密码",
            },
          ]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          {/* htmlType="submit点击登陆按钮"进行表单验证功能 */}
          <Button type="primary" htmlType="submit" style={{ width: "270px" }}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
